/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.omesoft.hksnore.util.ble;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.LayoutInflater;

import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.handler.MyHandlerUtil;
import com.omesoft.hksnore.util.photo.SettingUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;


/**
 * @author omesoft_lgc
 * @date 2015-9-25 下午3:52:13
 */
@SuppressLint("NewApi")
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    public static String mBluetoothDeviceAddress = null;
    private BluetoothGatt mBluetoothGatt;
    /*----------------------------------------------------------------------------------------------------------*/
    public final static String ACTION_GATT_CONNECTED = "com.omesoft.hksnore.util.ble.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.omesoft.hksnore.util.ble.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.omesoft.hksnore.util.ble.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE = "com.omesoft.hksnore.util.ble.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA_W = "com.omesoft.hksnore.util.ble.EXTRA_DATA_WEIGHT";
    public final static String EXTRA_DATA_R = "com.omesoft.hksnore.util.ble.EXTRA_DATA_RESISTOR";
    public final static String EXTRA_DATA_B = "com.omesoft.hksnore.util.ble.EXTRA_DATA_BYTE";
    /*----------------------------------------------------------------------------------------------------------*/
    protected BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothGattCallback mGattCallback;
    public static int BTState = 1;// 1:设备已断开。2:设备已连接.3:搜索设备中... 4:设备不支持蓝牙4.0
    // 5传送数据
    protected boolean isOnServiceConnected = false;
    private boolean mScanning = false;
    private Handler handler = new Handler();
    private boolean isExist = true;
    public static boolean foundService = false;
    // 系统锁
    private WakeLock wakeLock = null;
    public static boolean iserror = false;
    public static boolean isDisconnect = false;
    private int isSetBlue = 0;
    public static int DROPMEASURE = -1;// 测量的标识符 0 单次测量 8 停止测量

    /*----------------------------------------------------------------------------------------------------------*/
    public static int WBPMODE = 1;// 设备的标识符，0 不带按钮的，1 带按钮
    public static boolean isconnectBle = false;
    public static int BTBattery = 0;// 0-3等级
    public static int TEMPSTATE = 0;
    public Object obStr = "0";

    /*----------------------------------------------------------------------------------------------------------*/
    protected boolean isOpenSetTimer = true;
    protected final int SETSEVICECONNECT = 1111;

    private Config config;

	/*----------------------------------------------------------------------------------------------------------*/

    private void setLeScanCallback() {
        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi,
                                 final byte[] scanRecord) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        String deviceName = device.getName();
                        if (deviceName == null) {
                            return;
                        }
                        deviceName = deviceName.trim();
                        Log.e("muk", "设备名称>>>>>" + deviceName);
                            BTState = 3;
                        if (SampleGattAttributes.isEqualName(deviceName)
                                && mScanning) {
                            setBLEService(device.getAddress());
                        }
                    }
                });
            }
        };
    }

    private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            System.out.println("action..." + action);
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                Log.e("gh", "ACTION_GATT_CONNECTED.../搜索蓝牙//////////");
                SettingUtil.isOpenBle = true;
                BTState = 3;
                if (config.getMainHandler() != null) {
                    MyHandlerUtil.sendMsg(SettingUtil.BLE_SEACH,
                            config.getMainHandler(), null);
                }
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                    .equals(action)) {
                Log.e("gh", "ACTION_GATT_DISCONNECTED...关闭蓝牙///////////");
                BTState = 1;
                Log.e("lgc", "关闭蓝牙==============" + isExist);
                disconnect();
                close();
                cleanTempValue();
                // if (mBluetoothAdapter.isEnabled()) {
                if (isExist) {
                    initBLE();
                }
                // } else {
                // // SettingUtil.isFirstPhoneopenBle = true;
                // }
                SettingUtil.isOpenBle = false;
                isDisconnect = true;
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        isDisconnect = false;
                    }
                }, 500);
//				if (config.getMainHandler() != null) {
//					MyHandlerUtil.sendMsg(SettingUtil.BLE_DIS,
//							config.getMainHandler(), null);
//				}
                BTState = SettingUtil.BLE_DIS;
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                    .equals(action)) {
                Log.e("gh", "ACTION_GATT_SERVICES_DISCOVERED...发现蓝牙///////////");
                BTState = 2;
                isconnectBle = true;
                displayGattServices(getSupportedGattServices());
                foundService = true;
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                Log.e("gh", "ACTION_DATA_AVAILABLE...传输数据///////1////");

                BTState = 2;
                if (isconnectBle) {
                    isconnectBle = false;
                }
                byte[] datas = intent.getExtras().getByteArray(
                        BluetoothLeService.EXTRA_DATA_B);
                if (datas == null) {
                    return;
                }
                Log.e("gh", "ACTION_DATA_AVAILABLE...传输数据////2///////"
                        + datas.length);
                resolveBPData2(datas);

            } else if ("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED"
                    .equals(action)) {
                // ps: 好像这个方法有时候没有执行~~，先放着
                Log.e("lgc",
                        "----------------CONNECTION_STATE_CHANGED=====蓝牙状态发生改变1=========---------------------");

            } else if ("android.bluetooth.adapter.action.STATE_CHANGED"
                    .equals(action)) {
                isSetBlue++;
                Log.e("lgc",
                        "-----------------STATE_CHANGED=====蓝牙状态发生改变2=========--很奇怪耶------------------------------");
                if (isSetBlue == 1) {
                    if (!mBluetoothAdapter.isEnabled()) {

                        cleanTempValue();
                    }
                }
                if (isSetBlue == 2) {
                    isSetBlue = 0;
                }

            }
        }

    };

    /**
     * 解析数据
     *
     * @param datas
     */
    private List<Integer> bpDataList = new ArrayList<Integer>();

    private synchronized void resolveBPData2(byte[] datas) {
        Log.e("sha",
                "解析数据>>>-------------------------------start---------------------------------------------------------");
        try {
            for (int i = 0; i < datas.length; i++) {
                // if (datas[i] < 0)
                // bpDataList.add(datas[i] + 256);
                // else
                bpDataList.add((int) datas[i]);
            }
            int length = bpDataList.size();
            String str = "";
            for (int i = 0; i < length; i++) {
                str += bpDataList.get(i) + " , ";

            }
            int id = 0;
            if (bpDataList.get(2) < 0) {
                id = bpDataList.get(2) + 256;
            } else {
                id = bpDataList.get(2);
            }
            switch (id) {
                case 129:// 加速度数据

                    // Log.e("a1",
                    // "加速度数据----------------------------------------------------------------------------------------");
                    int tempX = bpDataList.get(4) * 256 + bpDataList.get(5);
                    tempX = (int) Math.pow(tempX, 2);// x的y次方
                    int tempY = bpDataList.get(6) * 256 + bpDataList.get(7);
                    tempY = (int) Math.pow(tempY, 2);// x的y次方
                    int tempZ = bpDataList.get(8) * 256 + bpDataList.get(9);
                    tempZ = (int) Math.pow(tempZ, 2);// x的y次方

                    int tempTotal = tempX + tempY + tempZ;

                    double tempData = Math.sqrt(tempTotal);
                    BigDecimal b = new BigDecimal(tempData);
                    // 保留2位小数
                    tempData = b.setScale(2, BigDecimal.ROUND_HALF_UP)
                            .doubleValue();
                    if (config.getMainHandler() != null) {
                        Log.e("sha", "收到的数据。。1。>>");
                        MyHandlerUtil.sendMsg(0, config.getMainHandler(), tempData);
                    }

                    break;
                case 130:// 加速度传感器校准

                    Log.e("b1",
                            "加速度传感器校准>>----------------------------------------------------------------------------------------");
                    break;
                case 131:// 振子控制

                    Log.e("c1",
                            "振子控制>>>---------------------------------------------------------------------------------bpDataList.get(4)::"
                                    + bpDataList.get(4));
                    break;
                case 132:// 查询电池状态

                    Log.e("d1",
                            " 查询电池状态>>>-----------------------------------bpDataList.get(4)::"
                                    + bpDataList.get(4)
                                    + "-----------------------------------bpDataList.get(5)::"
                                    + bpDataList.get(5));
                    break;
                case 133:// 查询音频模块状态

                    Log.e("e1",
                            "查询音频模块状态>>>--------------------------------------------------------------------------bpDataList.get(4)::"
                                    + bpDataList.get(4));
                    break;
                case 134:// 控制音频模块

                    Log.e("f1",
                            " 控制音频模块>>>-------------------------------------------------------------------------bpDataList.get(4)::"
                                    + bpDataList.get(4));

                    break;

                default:
                    break;
            }
            Log.e("test", "str::[" + str + "]");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bpDataList.clear();
        }

        Log.e("sha",
                "解析数据>>>-------------------------------end---------------------------------------------------------");

    }

    /**
     * 清除临时变量
     */
    private void cleanTempValue() {
        isOpenSetTimer = true;

    }

    /**
     * 初始化蓝牙
     */
    public void initBLE() {
        clearBT();
        // 判断是否支持BTE
        if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            BTState = 4;
            return;
        }
        Log.e("test", " =scanLeDevice。搜索。。。。。。。。::");
        // 获取adapter
        if (mBluetoothManager == null)
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothAdapter == null)
            mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.d("test", "mBluetoothAdapter == null");
            BTState = 4;
            return;
        }
        setLeScanCallback();
        scanLeDevice(true);
    }

    /**
     * 清除蓝牙
     */
    public void clearBT() {
        if (getAndroidSDKVersion() >= 18) {
            Log.e("test", "clearBT =清除蓝牙。停止搜索= isOnServiceConnected::"
                    + isOnServiceConnected);
            if (isOnServiceConnected) {
                isOnServiceConnected = false;
                foundService = false;
                scanLeDevice(false);
                BTState = 1;
                isOpenSetTimer = true;
            }
        } else {
            BTState = 4;
        }
    }

    /*
     * 搜索蓝牙
     */
    protected void scanLeDevice(final boolean enable) {
        if (mBluetoothAdapter != null) {
            if (enable) {
                Log.e("test", " =scanLeDevice。搜索。。。。。。。。::");
                mBluetoothAdapter.startLeScan(mLeScanCallback);
//				 BTState = 3;
                mScanning = true;
            } else {
                Log.e("test", " =scanLeDevice。关闭搜索。。。。。。。。::");
                if (mLeScanCallback != null)
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                mScanning = false;
            }
        }
    }

    /**
     * 获取系统版本
     *
     * @return
     */
    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
        }
        return version;
    }

    /**
     * 连接地址
     *
     * @param mDeviceAddress
     */
    private synchronized void setBLEService(String mDeviceAddress) {
        System.out.println("mScanning.1..:" + mScanning);
        if (mScanning) {
            scanLeDevice(false);
        }

        System.out.println("isOnServiceConnected 1..." + isOnServiceConnected);
        if (!isOnServiceConnected) {
            isOnServiceConnected = connect(mDeviceAddress);

            System.out.println("isOnServiceConnected 2..."
                    + isOnServiceConnected);
        }
    }

    /**
     * 匹配蓝牙UUID 发送通知 执行了这里的话，代表可以传输数据了
     *
     * @param gattServices
     */

    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null)
            return;
        String uuid = null;
        System.err.println("ACTION_GATT_SERVICES_DISCOVERED");
        Log.e("tets", "tets/..displayGattServices..................");
        for (BluetoothGattService gattService : gattServices) {
            uuid = gattService.getUuid().toString();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                uuid = gattCharacteristic.getUuid().toString();
                System.err.println("uuid：：" + uuid);
                if (uuid.equals(SampleGattAttributes.GetCharacteristicIDfbb1)) {
                    System.err.println("-----------------1------------------");
                    setCharacteristicNotification(gattCharacteristic, true);
                    readCharacteristic(gattCharacteristic);

                    return;
                }
                if (uuid.equals(SampleGattAttributes.GetCharacteristicIDfbb1)) {
                    Log.e("tets",
                            "tets/....displayGattServices2.........2222.......");

                    setCharacteristicNotification(gattCharacteristic, true);

                    return;
                }
            }
        }

    }

    private IntentFilter getFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        filter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);

        filter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        filter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");

        return filter;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /***
     * 获取系统锁
     */
    private void acquireWakeLock() {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
                    .getClass().getCanonicalName());
            wakeLock.acquire();
        }
    }

    /***
     * 释放系统锁
     */
    private void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.e(TAG, "蓝牙线程开始 onStart~~~");
        super.onStart(intent, startId);
        config = (Config) getApplicationContext();
//		 inflater = LayoutInflater.from(config);
        if (getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            setBluetoothGattCallback();
        }
        registerReceiver(mGattUpdateReceiver, getFilter());
        initBLE();
        // 获得系统锁
        this.acquireWakeLock();

    }

    @Override
    public void onDestroy() {




        super.onDestroy();
        isExist = false;
        stopSelf();
        releaseWakeLock();
        clearBT();
        // cencelTimer();
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
    }

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action,
                                 final BluetoothGattCharacteristic characteristic) {
        final Intent intent = new Intent(action);
        Log.d("test", "====broadcastUpdate>>>>>>>"
                + characteristic.getUuid().toString());
        if (SampleGattAttributes.GetCharacteristicIDfbb1.equals(characteristic
                .getUuid().toString())) {
            int flag = characteristic.getProperties();
            int format = -1;
            if ((flag & 0x01) != 0) {
                format = BluetoothGattCharacteristic.FORMAT_UINT16;
                Log.d(TAG, "UINT16.");
            } else {
                format = BluetoothGattCharacteristic.FORMAT_UINT8;
                Log.d(TAG, "UINT8.");
            }
            // 接收字节数组返回
            final byte[] datas = characteristic.getValue();
            Log.d("test", "====broadcastUpdate>>>>1>>>" + datas.length);
            intent.putExtra(EXTRA_DATA_B, datas);
        } else {
            // For all other profiles, writes the data formatted in HEX.
            final byte[] data = characteristic.getValue();
            if (data != null && data.length > 0) {
                final StringBuilder stringBuilder = new StringBuilder(
                        data.length);
                for (byte byteChar : data)
                    stringBuilder.append(String.format("%02X ", byteChar));
                Log.d("test", "====broadcastUpdate>>2>>>>>");
                intent.putExtra(EXTRA_DATA_W, new String(data) + "\n"
                        + stringBuilder.toString());
            }
        }
        sendBroadcast(intent);
    }

    public class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("test", "onUnbind");
        close();
        return super.onUnbind(intent);
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local BluetoothBroadcastReceiver adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter
        // through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                Log.e(TAG, "Unable to initialize BluetoothManager.");
                return false;
            }
        }

        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }

        return true;
    }

    /**
     * Connects to the GATT server hosted on the BluetoothBroadcastReceiver LE
     * device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The
     * connection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.e(TAG,
                    "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        if (mBluetoothDeviceAddress != null
                && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.e(TAG,
                    "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter
                .getRemoteDevice(address);
        MySharedPreferencesUtil.setMac(getApplicationContext(),device.toString());

        if (device == null) {
            Log.e(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the
        // autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(BluetoothLeService.this, false,
                mGattCallback);
        Log.w(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        return true;
    }

    /**
     * Disconnects an existing connection or cancel a pending connection. The
     * disconnection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public void disconnect() {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        Log.d("test", " mBluetoothGatt.disconnect()");
        mBluetoothGatt.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure
     * resources are released properly.
     */
    public void close() {
        if (mBluetoothGatt == null) {
            return;
        }
        Log.d("test", "mBluetoothGatt.close()");
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

    /**
     * Request a read on a given {@code BluetoothGattCharacteristic}. The read
     * result is reported asynchronously through the
     * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
     * callback.
     *
     * @param characteristic The characteristic to read from.
     */
    public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
        Log.e("test", "readCharacteristic");
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        mBluetoothGatt.readCharacteristic(characteristic);
    }

    public void writeCharacteristic(byte[] data) {
        Log.e("test",
                "写入    writeCharacteristic>>----------------------------------------------------------------------------------------");
//		try {
        if (mBluetoothAdapter == null || mBluetoothGatt == null
                || data == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        BluetoothGattService myBluetoothGattService = null;
        myBluetoothGattService = mBluetoothGatt.getService(UUID
                .fromString(SampleGattAttributes.SeviceIDfbb0));
        BluetoothGattCharacteristic mBluetoothGattCharacteristic = null;
        mBluetoothGattCharacteristic = myBluetoothGattService
                .getCharacteristic(UUID
                        .fromString(SampleGattAttributes.GetCharacteristicIDfbb3));
        // mBluetoothGattCharacteristic.setValue(crcCheck(data));
        mBluetoothGattCharacteristic.setValue(data);
        mBluetoothGatt.writeCharacteristic(mBluetoothGattCharacteristic);
        Log.e("test",
                "写入完成>>----------------------------------------------------------------------------------------");
//		} catch (Exception e) {
//			// TODO: handle exception
//			Log.e("test",
//					"写入异常>>----------------------------------------------------------------------------------------");
//		}
    }

    /**
     * 校验和
     *
     * @param datas
     * @return
     */
    private byte[] crcCheck(byte[] datas) {
        // crc校验
        if (datas == null || datas.length < 3) {
            return null;
        }
        byte crc = 0x00;
        Log.d("test", "发送-----------start-");
        for (int i = 1; i < datas.length - 1; i++) {
            Log.d("test", "发送：：" + datas[i]);
            crc += datas[i];
        }
        Log.d("test", "发送-----------end-");
        Log.d("test", "发送crc：：" + crc);
        datas[datas.length - 1] = crc;
        return datas;
    }

    private void setBluetoothGattCallback() {
        mGattCallback = new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                String intentAction;
                Log.e(TAG, "onConnectionStateChange:-改变--");
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    intentAction = ACTION_GATT_CONNECTED;
                    // BTState = 2;

                    broadcastUpdate(intentAction);
                    Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    System.err.println("Disconnected from GATT server.");
                    intentAction = ACTION_GATT_DISCONNECTED;
                    broadcastUpdate(intentAction);
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {

                System.out.println("onServicesDiscovered..............=============");

                Log.e(TAG, "onServicesDiscovered:---");
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                } else {
                    Log.e(TAG, "onServicesDiscovered 有异常出现: " + status);
                }
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                System.out.println("onCharacteristicChanged..............===============");
                Log.e(TAG, "onCharacteristicChanged:");
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                System.out.println("onCharacteristicRead..............==========");
                Log.e("test", "onCharacteristicRead---");
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.e("test", "BluetoothGatt.GATT_SUCCESS");
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                }
            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicWrite(gatt, characteristic, status);
                System.out
                        .println("onCharacteristicWrite......接收........==========");
                Log.e("test", "onCharacteristicWrite----");
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d("test", "BluetoothGatt.GATT_SUCCESS");
                    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
                }
            }

            @Override
            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                Log.e("test", "onDescriptorWrite--");
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.e(TAG, "Callback: Wrote GATT Descriptor successfully.");
                } else {
                    Log.e(TAG, "Callback: Error writing GATT Descriptor: " + status);
                }
            }

            ;
        };

    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification. False otherwise.
     */
    public void setCharacteristicNotification(
            BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            Log.e("tets",
                    "tets/....setCharacteristicNotification.........null.......");
            return;
        }
        Log.e("tets", "characteristic.getUuid().toString()：：end" + characteristic.getUuid().toString());
        boolean flv = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        Log.e("tets", "发送通知的情况::::::" + flv);
        if (SampleGattAttributes.GetCharacteristicIDfbb1.equals(characteristic.getUuid().toString())) {

            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));

            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            if (mBluetoothGatt.writeDescriptor(descriptor)) {
                Log.d("tets", "写入       mBluetoothGatt.writeDescriptor==true");
            } else {
                Log.d("tets", "写入       mBluetoothGatt.writeDescriptor==false");
            }
        }
    }

    /**
     * Retrieves a list of supported GATT services on the connected device. This
     * should be invoked only after {@code BluetoothGatt#discoverServices()}
     * completes successfully.
     *
     * @return A {@code List} of supported services.
     */
    public List<BluetoothGattService> getSupportedGattServices() {
        if (mBluetoothGatt == null)
            return null;

        return mBluetoothGatt.getServices();
    }

}
